package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorSerivce;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorSerivce dishFlavorSerivce;

    /**
     * 新增菜品，同时保存对应的口味数据
     *
     * @param dishDto
     */

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        // 保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        // 保存菜品口味数据到 口味表
        // 集合，批量保存， 这其中 dishflaor 的id 没有封装上

        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> newfloavors = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());

        dishFlavorSerivce.saveBatch(newfloavors);


    }

    /**
     * 根据id 查询菜品对应信息，和口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavorList = dishFlavorSerivce.list(queryWrapper);
        dishDto.setFlavors(flavorList);

        return dishDto;
    }

    @Override
    public void updateWithFlaor(DishDto dishDto) {
        this.updateById(dishDto);
        //方案。先把原先口味数据清理， 再添加新的
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorSerivce.remove(queryWrapper);

        // 但此时，flavors  dish_id 没有值
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> newfloavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        // 批量保存
        dishFlavorSerivce.saveBatch(newfloavors);

    }
}
